﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Objects;
using System.Linq;
using VO.Entities;

namespace VO.Business.Controllers
{
    public static class TracksCategoriesController
    {
        public static List<TrackCategory> GetTracksCategories()
        {
            using (ModelVOContainer ctx = new ModelVOContainer())
            {
                return ctx.TrackCategories.ToList();
            }
        }

        public static TrackCategory GetTrackCategory(int id)
        {
            using (ModelVOContainer ctx = new ModelVOContainer())
            {
                return ctx.TrackCategories.SingleOrDefault(p => p.Id == id);
            }
        }

        public static bool SaveTrackCategory(TrackCategory trackCategory, bool isnew)
        {
            using (ModelVOContainer ctx = new ModelVOContainer())
            {
                trackCategory.LastEditDate = DateTime.Now;

                try
                {
                    ctx.TrackCategories.Attach(trackCategory);
                    if (isnew)
                    {
                        trackCategory.CreatedDate = DateTime.Now;
                    }
                    ctx.ObjectStateManager.ChangeObjectState(trackCategory, isnew ? EntityState.Added : EntityState.Modified);

                    return ctx.SaveChanges() > 0;
                }
                catch (OptimisticConcurrencyException exOpt)
                {
                    ctx.Refresh(RefreshMode.ClientWins, trackCategory);

                    return ctx.SaveChanges() > 0;
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }
    }
}
